<template>
  <div>
    <input type="text" v-model="keyword" placeholder="请输入关键词">
    <input type="button" value="查询" @click="btnfind(keyword)">
    <input type="button" value="新增" @click="btnAdd">
  </div>
  <table>
    <thead>
      <tr>
        <th>id</th>
        <th>标题</th>
        <th>作者</th>
        <th>操作</th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="item in booksList":key="item.id">
        <td>{{ item.id }}</td>
        <td>{{ item.bookName }}</td>
        <td>{{ item.bookAuthor }}</td>
        <td>
          <input type="button" value="编辑" @click="btnEdit(item.id)">
          <input type="button" value="删除" @click="btnDel(item.id)">
        </td>
      </tr>
    </tbody>
  </table>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
// import { books } from '@/mock/db';
import { delBook, find, getAll } from '@/api/bookApi';
let keyword = ref('');
let router = useRouter()
let booksList = reactive([])

// ///////////
async function btnfind(keyword){
  console.log('查询');
  let res = await find(keyword)
  
  booksList.splice(0,booksList.length,...res.data)
}
function btnAdd(){
  console.log('新增');
  router.push('/BookAdd')
}
function btnEdit(id){
  console.log('编辑',id);
  router.push(`/BookEdit/${id}`)
  
}
function btnDel(id){
  console.log('删除',id);
  if(confirm(`是否删除${id}`)){
    delBook(id);
    let idx = booksList.findIndex(item => item.id===id);
    booksList.splice(idx,1)
  }
  
}

onMounted(async () => {
  let res = await getAll();
  console.log(res);
  
  booksList.push(...res.data)
})
</script>

